const fdUriEn = 'http://www.stardict.org/lookup-backend.php';
const fdUriCn = 'http://www.stardict.cn/define-backend.php';

const pydb = 'py.sqlite';

// TODO: select the right stardict website uri according to locale
var uri = fdUriEn;

var mainWin = null;
var foxydict = null;

function sbdump(msg)
{
  dump('FoxyDict Sidebar: ' + msg + '\n');
};

function refreshMenulist()
{
    let menulist = document.getElementById('menuHistory');
    menulist.removeAllItems();
    for (var i = 0; i < foxydict.fdHistory.length; i++)
    {
      let word = foxydict.fdHistory[foxydict.fdHistory.length - i - 1];
      menulist.appendItem(word, word, null);
    }

    let word = foxydict.fdHistory[foxydict.fdHistory.length - 1];
    menulist.label = word;
    menulist.value = word;

    return word;
};

function makeRequest(uri)
{
       let httpRequest;

       if (window.XMLHttpRequest) { // Mozilla, Safari, ...
	   httpRequest = new XMLHttpRequest();
	   if (httpRequest.overrideMimeType) {
	       httpRequest.overrideMimeType('text/xml');
	       // See note below about this line
	   }
       } 
       else if (window.ActiveXObject) { // IE
	   try {
	       httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
	   } 
	   catch (e) {
	       try {
		   httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
	       } 
	       catch (e) {}
	   }
       }

       if (!httpRequest) {
	   dump('Giving up :( Cannot create an XMLHTTP instance\n');
	   return false;
       }
       httpRequest.onreadystatechange = function() { onSuccess(httpRequest); };
       httpRequest.open('GET', uri, true);
       httpRequest.send('');
};

function onSuccess(request)
{
      if (request.readyState == 4 && request.status == 200)
      {
        document.getElementById('fdDefineContents')
  	        .contentDocument.getElementById('fdDefines')
	        .innerHTML = request.responseText;
	
	let pinyin = getPinyin(document.getElementById('menuHistory').label);
	if (Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefService).getBranch('extensions.foxydict.')
	              .getBoolPref('statusbarpinyin'))
  	  mainWin.document.getElementById('pinyin').value = pinyin.join(' ');
      }
};

function pageOnLoad()
{
  sbdump('page loaded');
  try
  {
    mainWin = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
    		    .getInterface(Components.interfaces.nsIWebNavigation)
		    .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
		    .rootTreeItem
		    .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
		    .getInterface(Components.interfaces.nsIDOMWindow);
    foxydict = mainWin.foxydict;

    if (!foxydict.fdHistory.length)	return;

    let word = refreshMenulist();
    makeRequest(uri + '?q=' + encodeURIComponent(word));

  } catch (e) { sbdump('Exception: ' + e); }
};

function submit(event)
{
  if (event.keyCode != 13 /* DOM_VK_RETURN */)	return;

  if (!foxydict) throw 'foxydict in sidebar not initialized';

  let word = document.getElementById('menuHistory').label;
  foxydict.add2history(word);
  refreshMenulist();
  makeRequest(uri + '?q=' + encodeURIComponent(word));
};

function selectWord(event)
{
  let word = event.target.label;
  foxydict.add2history(word);
  refreshMenulist();
  makeRequest(uri + '?q=' + encodeURIComponent(word));
};

function getPinyin(word)
{
  try {

	let unic = word.charCodeAt(0);

	// get pinyin from unicode
	if (unic == 0x3007 || (unic > 0x4E00 && unic < 0x9FA5))
	{
	  let file = Components.classes['@mozilla.org/file/directory_service;1']
	  		       .getService(Components.interfaces.nsIProperties)
			       .get('ProfD', Components.interfaces.nsIFile);
	//  file.append('/extensions/FoxyDict@xieluyun/chrome/content/py.sqlite');
	  file.append('py.sqlite');
	  let dbconn = Components.classes['@mozilla.org/storage/service;1']
	  			 .getService(Components.interfaces.mozIStorageService)
				 .openDatabase(file);
	  let statement = dbconn.createStatement('select Pinyin from Uni2Pinyin where Unic=?1');
	  statement.bindInt32Parameter(0, unic);
	  statement.executeStep();
	  var pinyin = statement.getString(0).split('-');
	  
	  if (!pinyin.length) return;
	  
	  var _a = ['\u0101', '\u00E1', '\u01CE', '\u00E0', 'a'];
	  var _e = ['\u0113', '\u00E9', '\u011B', '\u00E8', 'e'];
	  var _i = ['\u012B', '\u00ED', '\u01D0', '\u00EC', 'i'];
	  var _o = ['\u014D', '\u00F3', '\u01D2', '\u00F2', 'o'];
	  var _u = ['\u016B', '\u00FA', '\u01D4', '\u00F9', 'u'];
	  var _v = ['\u01D6', '\u01D8', '\u01DA', '\u01DC', '\u00FC'];

	for( j = 0; j < pinyin.length; j++){
		pin = pinyin[j];
		tone = 4;

		if( pin.indexOf("1") != -1 ) tone = 0;
		else if( pin.indexOf("2") != -1 ) tone = 1;
		else if( pin.indexOf("3") != -1 ) tone = 2;
		else if( pin.indexOf("4") != -1 ) tone = 3;
		
		if( pin.indexOf("a") != -1 ) pin = pin.replace( "a", _a[tone] );
		else if( pin.indexOf("e") != -1 ) pin = pin.replace( "e", _e[tone] );
		else if( pin.indexOf("ou") != -1 ) pin = pin.replace( "o", _o[tone] );
		else {
		for( k = pin.length - 1; k >= 0; k--){
			if( pin[k] == 'a' || pin[k] == 'e' || pin[k] == 'i' || pin[k] == 'o' || pin[k] =='u' ){
				switch(pin[k]){
				 case 'i':  pin = pin.replace( "i", _i[tone] ); break;
				 case 'o':  pin = pin.replace( "o", _o[tone] ); break;
				 case 'u':  if( k+1 < pin.length - 1 && pin[k+1] == ":" ) pin = pin.replace( "u:", _v[tone] ); 
					     else pin = pin.replace( "u", _u[tone] ); break;
				 default: alert("some kind of wierd vowel");
				}
				break;
			}
		 }
	      }
	    pinyin[j] = pin.substring(0, pin.length - 1);//strip the number
	    }
	    return pinyin;
	}
  } catch (e) {
	  sbdump('Pinyin error: ' + e);
  }
};
